using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using IceDog.WebApi.AnythingApi.AppExtensions;
using IceDog.WebApi.AnythingApi.CustomMiddlewares;
using IceDog.WebApi.AnythingApi.Mapping;
using IceDog.WebApi.AnythingApi.Utils;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;

namespace IceDog.WebApi.AnythingApi
{
    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddControllers()
            //    .AddJsonOptions(options =>
            //{
            //    options.JsonSerializerOptions.AllowTrailingCommas = true;
            //});
            services.AddMvc()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss.FFFFFFFK";
                });
            services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllers()
                .ConfigureApiBehaviorOptions(options =>
                {
                    //禁止使用表单文件参数的约束
                    options.SuppressConsumesConstraintForFormFileParameters = true;
                    //禁止为参数推断绑定源
                    options.SuppressInferBindingSourcesForParameters = true;
                    //禁止模型状态无效筛选器
                    options.SuppressModelStateInvalidFilter = true;
                    //禁止映射客户端错误
                    options.SuppressMapClientErrors = true;
                    //客户端错误映射
                    options.ClientErrorMapping[404].Link = "https://httpstatuses.com/404";
                });
            ServicesAddSwaggerGen(services);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseWhen(context =>
            {
                return true;
            }, builder =>
            {
                var accessor = builder.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
                WebHelper.SetHttpContextAccessor(accessor);
            });
            //app.UseHttpsRedirection();
            //app.UseAuthorization();

            app.UseDefaultFiles();
            app.UseStaticFiles();
            var rewriterOptions = new Microsoft.AspNetCore.Rewrite.RewriteOptions();
            //rewriterOptions.Rules.Add();
            //app.UseRewriter(rewriterOptions);
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                /*
                endpoints.MapGet("/",context =>
                {
                    context.Response.WriteAsync("");
                    return Task.CompletedTask;
                });
                */
            });
            AppUseSwagger(app);
        }

        #region ConfigureServices 详细的添加内容
        /// <summary>
        /// 添加swagger gen
        /// </summary>
        /// <param name="services"></param>
        private void ServicesAddSwaggerGen(IServiceCollection services)
        {
            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(options =>
            {
                var title = "Anything API";
                var license = new OpenApiLicense()
                {
                    Name = "GPL V3",
                    Url = new Uri("https://www.example.com/gpl_v3.html")
                };
                var contact = new OpenApiContact()
                {
                    Name = "DHclly",
                    Email = "335121817@qq.com",
                    Url = new Uri("https://www.example.com/contact_me.html")
                };
                var description = "this project use for test WebApi Anything";
                options.SwaggerDoc("version_1", new OpenApiInfo
                {

                    Title = title,
                    Version = "v1.0",
                    License = license,
                    Contact = contact,
                    Description = description
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    options.IncludeXmlComments(xmlPath);
                }
                //所有参数变量用camelCase
                options.DescribeAllParametersInCamelCase();
            });
        }
        #endregion

        #region Configure 详细的添加内容
        /// <summary>
        /// app use swagger
        /// </summary>
        /// <param name="app"></param>
        private void AppUseSwagger(IApplicationBuilder app)
        {
            //app.UseCacheSwaggerFileMiddleware();
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(options=> {
                options.RouteTemplate = "api-docs/{documentName}/swagger.json";
            });
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("version_1/swagger.json", "Anything API Version 1.0");
                options.RoutePrefix = "api-docs";
                var c = options.ConfigObject;
            });
        }
        #endregion
    }
}
